package org.summerframework.component.security.spring.matcher;

import org.summerframework.component.security.annotion.LoginRequired;
import org.summerframework.component.security.annotion.RoleRequired;
import org.summerframework.core.util.AnnotationUtils;
import org.summerframework.core.util.HandlerMethodUtil;
import org.summerframework.core.util.SpringContextUtil;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author 石超
 * @version v1.0.0
 */
public class RoleRequestMatcher implements RequestMatcher {
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public boolean matches(HttpServletRequest request) {
        HandlerExecutionChain handler = HandlerMethodUtil.getHandlerMethod(getRequestMappingHandlerMapping(), request);

        if (handler != null && handler.getHandler() instanceof HandlerMethod) {
            return AnnotationUtils.hasAnnotation((HandlerMethod) handler.getHandler(), Arrays.asList(LoginRequired.class, RoleRequired.class, PreAuthorize.class, PostAuthorize.class, PreFilter.class));
        }

        return false;
    }

    private RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        if (requestMappingHandlerMapping == null) {
            requestMappingHandlerMapping = SpringContextUtil.getBean(RequestMappingHandlerMapping.class);
        }
        return requestMappingHandlerMapping;
    }
}
